import React, { useCallback } from 'react';
import { Avatar, Button, Space } from 'antd';
import { Conversations } from '@ant-design/x';
import { GetProp } from 'antd/es';
import { PlusOutlined, UserOutlined, LogoutOutlined, SettingOutlined } from '@ant-design/icons';
import { history, useModel } from '@umijs/max';
import { stringify } from 'querystring';
import { flushSync } from 'react-dom';
import HeaderDropdown from '@/components/HeaderDropdown';
import { userLogout } from '@/services/backend/userController';
import { MenuInfo } from 'rc-menu/lib/interface';
import menu from 'antd/es/menu';

interface SidebarProps {
  styles: any;
  conversationsItems: any[];
  setConversationsItems: React.Dispatch<React.SetStateAction<any[]>>;
  activeKey: string;
  setActiveKey: React.Dispatch<React.SetStateAction<string>>;
}

const Sidebar: React.FC<SidebarProps> = ({
  styles,
  conversationsItems,
  setConversationsItems,
  activeKey,
  setActiveKey,
}) => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};

  const onAddConversation = () => {
    // 添加新会话时，不需要立即创建memoryId
    // memoryId将在第一次发送消息时创建
    const newKey = `${conversationsItems.length}`;
    setConversationsItems([
      ...conversationsItems,
      {
        key: newKey,
        label: `New Conversation ${conversationsItems.length}`,
      },
    ]);
    setActiveKey(newKey);
  };

  const onConversationClick: GetProp<typeof Conversations, 'onActiveChange'> = (key) => {
    setActiveKey(key);
  };

  // 登出功能
  const loginOut = async () => {
    await userLogout();
    const { search, pathname } = window.location;
    const urlParams = new URL(window.location.href).searchParams;
    const redirect = urlParams.get('redirect');
    if (window.location.pathname !== '/user/login' && !redirect) {
      history.replace({
        pathname: '/user/login',
        search: stringify({
          redirect: pathname + search,
        }),
      });
    }
  };

  const onMenuClick = useCallback(
    (event: MenuInfo) => {
      const { key } = event;
      if (key === 'logout') {
        flushSync(() => {
          setInitialState((s) => ({ ...s, currentUser: undefined }));
        });
        loginOut();
        return;
      }
      history.push(`/account/${key}`);
    },
    [setInitialState],
  );

  const menuItems = [
    {
      key: 'center',
      icon: <UserOutlined />,
      label: '个人中心',
    },
    {
      key: 'settings',
      icon: <SettingOutlined />,
      label: '个人设置',
    },
    {
      type: 'divider' as const,
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: 'Logout',
    },
  ];

  const logoNode = (
    <div className={styles.logo}>
      <img src="/knowledge.png" draggable={false} alt="logo" />
      <span>dynabook Knowledge</span>
    </div>
  );

  return (
    <div className={styles.menu}>
      {/* Logo */}
      {logoNode}
      {/* 添加会话 */}
      <Button
        onClick={onAddConversation}
        type="link"
        className={styles.addBtn}
        icon={<PlusOutlined />}
      >
        New Conversation
      </Button>
      {/* 会话管理 */}
      <Conversations
        items={conversationsItems}
        className={styles.conversations}
        activeKey={activeKey}
        onActiveChange={onConversationClick}
      />
      <HeaderDropdown
        menu={{
          selectedKeys: [],
          onClick: onMenuClick,
          items: menuItems,
        }}
      >
        {/* 底部 */}
        <Space
          align="center"
          style={{
            marginBottom: '16px',
            padding: '12px',
            display: 'flex',
            justifyContent: 'start',
            width: '100%',
          }}
        >
          <Avatar size="small" icon={<UserOutlined />} style={{ backgroundColor: '#87d068' }} />
          <span
            className="anticon"
            style={{
              marginLeft: '2px',
              display: 'flex',
              flexDirection: 'column',
              justifyContent: 'center',
            }}
          >
            {currentUser?.userName ?? '无名'}
          </span>
        </Space>
      </HeaderDropdown>
    </div>
  );
};

export default Sidebar;
